﻿using A2.ERP.BLL;
using A2.ERP.Common;
using A2.ERP.IBLL;
using A2.ERP.Models;
using A2.ERP.Models.ViewModels;
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace A2.ERP.UI.Controllers
{
    public class LoginController : Controller
    {
        It_UserService t_UserService = new BLL.t_UserService();

        #region 登录

        public ActionResult Index()
        {
            return View();
        }
        //显示验证码
        public ActionResult Vlidate()
        {
            string vcode = CaptchHelper.CreatRandom(4);

            Session["vcode"] = vcode;

            byte[] bs = CaptchHelper.DrawImage(vcode, 20, Color.White);

            return File(bs, "image/jpeg");
        }

        [HttpPost]
        public ActionResult Index(string name, string pwd, string validateCode)
        {
            #region 非空验证
            if (name == null && pwd == null)
            {
                ViewBag.Vlidate = "不能为空";
                return View();
            }
            object scode = Session["vcode"];

            if (scode == null || scode.ToString() != validateCode)
            {
                ViewBag.Vlidate = "验证码错误";

                return View();
            }
            Session["vcode"] = null;
            #endregion

            LoginResult result = t_UserService.LoginValidate(name, pwd);

            //调用业务逻辑层
            if (result.Code == LoginCode.Success)
            {
                var uid = Guid.NewGuid().ToString("N");

                //这里还有应该将登录对象的状态改变
                t_UserService.UpdateEntity(new t_User { UserName = result.user.UserName, Token = uid }, i => i.Token);

                //还要在表里添加一条xx登录的数据


                HttpCookie cookie = new HttpCookie("uid")
                {
                    Value = uid,
                    Expires = DateTime.Now.AddDays(7)
                };

                Response.Cookies.Add(cookie);
                return Redirect("/Home/Index");
            }
            else
            {
                ViewBag.Vlidate = result.Message;
                return View();
            }
        }
        #endregion


    }
}
